package com.yc.tomcat.core;

import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class ClearSession implements Runnable{
	// 记录每个session的最后访问实际，以jsessionId为键，最后访问时间为值
	protected static Map<String, Date> clearMap = new Hashtable<String, Date>();

	@Override
	public void run() {
		Date now = null;
		
		Entry<String, Date> entry = null;
		while (true) {
			now = new Date();
			if (!clearMap.isEmpty()) {
				for (Iterator<Entry<String, Date>> iterator = clearMap.entrySet().iterator(); iterator.hasNext();) {
					entry = iterator.next();
					
					// 说明已过期
					if (now.getTime() - entry.getValue().getTime() > ContantInfo.SESSION_LIVE) {
						synchronized (TomcatServer.sessions) {
							// 通过sessionId移除
							TomcatServer.sessions.remove(entry.getKey());
							iterator.remove();
						}
					}
				}
			}
			
			try {
				Thread.sleep(ContantInfo.CLEAR_SESSION_CYCLE);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			clearMap.forEach((key, val) -> {
				System.out.println(key + " : " + val);
			});
		}
	}
}
